/*-
 * Copyright (c) 2009 Jonathan Anderson
 * All rights reserved.
 *
 * WARNING: THIS IS EXPERIMENTAL SECURITY SOFTWARE THAT MUST NOT BE RELIED
 * ON IN PRODUCTION SYSTEMS.  IT WILL BREAK YOUR SOFTWARE IN NEW AND
 * UNEXPECTED WAYS.
 * 
 * This software was developed at the University of Cambridge Computer
 * Laboratory with support from a grant from Google, Inc. 
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

#include <sys/capability.h>

#include <libcapsicum.h>
#include <libuserangel.h>

#include <err.h>
#include <errno.h>
#include <fcntl.h>
#include <poll.h>
#include <stdio.h>
#include <string.h>
#include <sysexits.h>
#include <unistd.h>



void run_sandbox();


int main(int argc, char *argv[])
{
	if(ld_insandbox())
	{
		run_sandbox();
		return 0;
	}


	// user angel connection for the sandbox
	int angel = ua_find();
	if(angel < 0) err(EX_SOFTWARE, "Couldn't find user angel");

	// user angel connection for me
	ua_find();


	// start the sandbox
	int me = open(argv[0], O_RDONLY);
	char *sargv[1] = { NULL };
	struct lc_sandbox *sandbox;

	if(lch_startfd(me, "test", sargv, LCH_PERMIT_STDOUT | LCH_PERMIT_STDERR,
	               NULL, &sandbox))
		err(EX_SOFTWARE, "Error starting sandbox");

	int sandsock = -1;
	if(lch_getsock(sandbox, &sandsock))
		err(EX_SOFTWARE, "Couldn't get sandbox socket");

	struct ua_datum *agent_datum = ua_marshall_string("user-angel", 10);
	if(ua_send(sandsock, agent_datum, &angel, 1) < 0)
		err(EX_IOERR, "Error sending user angel to sandbox");



	// cache an FD and send the cryptographic capability to the sandbox
	int fd = open("/etc/passwd", O_RDONLY);
	if(fd < 0) err(EX_SOFTWARE, "Error opening /etc/passwd");

	char *token;
	if(ua_cache_fd(fd, "passwd file", &token, 0))
		err(EX_SOFTWARE, "Error caching /etc/passwd FD");

	struct ua_datum *token_datum = ua_marshall_string(token, strlen(token));
	if(ua_send(sandsock, token_datum, &angel, 1) < 0)
		err(EX_IOERR, "Error sending FD token to sandbox");


	int childproc = 0;
	if(lch_getprocdesc(sandbox, &childproc))
		err(EX_SOFTWARE, "Error getting sandbox process descriptor");

	struct pollfd fds[] = {
		{ childproc, POLLHUP | POLLERR, 0 },
	};

	int count = poll(fds, 1, -1);
	if(count < 0) err(EX_SOFTWARE, "Error polling sandbox descriptor");

	return 0;
}


void run_sandbox()
{
	if(!ld_insandbox()) err(EX_SOFTWARE, "cap_main() not in sandbox");

	struct lc_host *lchpp;
	if(lcs_get(&lchpp) < 0) err(EX_SOFTWARE, "Error getting lc_host");

	int host;
	if(lcs_getsock(lchpp, &host) < 0)
		err(EX_SOFTWARE, "Error getting host socket");


	int32_t angel = -1;
	size_t angellen = 1;

	struct ua_datum *d = ua_recv(host, &angel, &angellen);

	if(!d) err(EX_IOERR, "Error receiving user angel");
	if(angellen != 1) err(EX_SOFTWARE, "angellen == %zu != 1", angellen);

	ua_set(angel);
	if(ua_ping()) err(EX_IOERR, "Error pinging user angel");


	d = ua_recv(host, NULL, 0);

	if(!d) err(EX_IOERR, "Error receiving FD token");
	if(angellen != 1) err(EX_SOFTWARE, "angellen == %zu != 1", angellen);

	char token[d->length + 1];
	size_t tokenlen = sizeof(token);
	if(ua_unmarshall_string(d, token, &tokenlen) < 0)
		err(EX_IOERR, "Error unmarshalling FD token");
/*
	size_t namelen = 128;
	char name[namelen];
*/
	int fd = ua_retrieve_fd(token);//, name, &namelen);
	if(fd < 0) err(EX_SOFTWARE, "Error retrieving cached FD");

	char buf[256];
	int bytes = read(fd, buf, sizeof(buf) - 2);
	if(bytes < 0) err(EX_IOERR, "Error reading from cached FD");

	printf("OK\n");
	fflush(stdout);

	return;
}

